package org.zhaozhen.order.service.impl;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.zhaozhen.basic.service.impl.BaseServiceImpl;
import org.zhaozhen.basic.util.CodeGenerateUtils;
import org.zhaozhen.basic.util.PageList;
import org.zhaozhen.order.domain.AdoptOrder;
import org.zhaozhen.order.domain.OrderAddress;
import org.zhaozhen.order.mapper.AdoptOrderMapper;
import org.zhaozhen.order.mapper.OrderAddressMapper;
import org.zhaozhen.order.query.AdoptOrderQuery;
import org.zhaozhen.order.service.IAdoptOrderService;
import org.zhaozhen.org.domain.Employee;
import org.zhaozhen.org.mapper.EmployeeMapper;
import org.zhaozhen.pay.constants.AlipayConstant;
import org.zhaozhen.pay.domain.PayBill;
import org.zhaozhen.pay.service.IPayBillService;
import org.zhaozhen.pet.domain.Pet;
import org.zhaozhen.pet.mapper.PetMapper;
import org.zhaozhen.quartz.constant.JobTypeConstants;
import org.zhaozhen.quartz.service.IQuartzService;
import org.zhaozhen.quartz.util.QuartzJobInfo;
import org.zhaozhen.user.domain.Logininfo;
import org.zhaozhen.user.domain.User;
import org.zhaozhen.user.domain.UserAddress;
import org.zhaozhen.user.mapper.UserAddressMapper;
import org.zhaozhen.user.mapper.UserMapper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    OrderAddressMapper orderAddressMapper;
    @Value("${order.last.pay.time}")//SPEL 获取配置文件中的值
    private Integer lastPayTime;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;


    @Override
    public String submit(Map<String, Object> param, Logininfo currentLogin) {
        //获取前端传来的数据
        //获取配送方式
        Integer serviceMethod = Integer.valueOf(param.get("service_method").toString());
        //获取地址编号
        Long addressId = Long.valueOf(param.get("address_id").toString());
        //获取支付方式
        Integer payMethod = Integer.valueOf(param.get("pay_method").toString());
        //获取宠物id
        Long petId = Long.valueOf(param.get("pet_id").toString());
        //空校验
        //宠物下架，设置下架时间
        Pet pet = petMapper.loadById(petId);
        pet.setOffsaletime(new Date());
        pet.setState(0);
        petMapper.update(pet);
        //生成领养订单
        //获取用户信息
        User user = userMapper.loadByLogininfo_id(currentLogin.getId());
        AdoptOrder order = initAdoptOrder(pet, user);
        //生成支付随机码
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        //保存领养订单
        adoptOrderMapper.save(order);
        //保存订单地址
        //获取用户的地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);
        //生成支付单
        PayBill payBill = new PayBill();
        payBill.setDigest("[摘要]对"+pet.getName()+"领养的支付单！");
        payBill.setMoney(order.getPrice());
        payBill.setUnionPaySn(order.getPaySn());
        payBill.setPayChannel(1L);
        payBill.setBusinessType(AlipayConstant.BUSINESS_TYPE_ADOPT);
        payBill.setBusinessKey(order.getId());
        payBill.setUser_id(user.getId());
        payBill.setShop_id(order.getShop_id());
        payBill.setNickName(user.getUsername());
        //保存支付单
        payBillService.add(payBill);
        //超时未支付自动取消 定时器
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        String jobName = JobTypeConstants.TIME_OUT_ADOPT_LAST_PAY + order.getId();
        jobInfo.setJobName(jobName);
        Map<String,Object> map = new HashMap<>();
        map.put("type",JobTypeConstants.TIME_OUT_ADOPT_LAST_PAY);
        map.put("orderId",order.getId());
        jobInfo.setParams(map);
        jobInfo.setFireDate(order.getLastPayTime());
        quartzService.addJob(jobInfo);
        //请求支付接口
        String payData = payBillService.pay(payBill);
        return payData;
    }



    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        order.setState(0);//待支付
        order.setPrice(pet.getSaleprice());//如果是服务订单 ,这里要乘上数量
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);//订单编号
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        System.out.println(lastPayTime);
        order.setLastPayTime(new Date(System.currentTimeMillis() + lastPayTime));
        return order;
    }


    @Override
    public PageList<AdoptOrder> queryAdmin(AdoptOrderQuery query, Logininfo currentLogin) {
        //获取登录人
        Employee employee = employeeMapper.loadByLogininfo_id(currentLogin.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void cancelByQuartz(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        if(adoptOrder != null ){
            if(adoptOrder.getState() == 0){//一定要是待支付才处理
                //主动去查询支付宝,是否存在支付  @TODO
                adoptOrder.setState(-1);
                adoptOrderMapper.update(adoptOrder);
            }
        }

    }

}
